//
//  PersonalInformationController.m
//  WuJieLive
//
//  Created by 张瀚坤 on 2017/10/26.
//  Copyright © 2017年 zhk. All rights reserved.
//

#import "PersonalInformationController.h"
#import "BrithDayView.h"
#import "ReferrerViewController.h"
#import "RealNameController.h"
#import "AreasPickerView.h"
#import "AuditRefuseController.h"
#import "ResultController.h"
#import "HDAreaChoiceView.h"
#import "NickNameViewController.h"

@interface PersonalInformationController ()
<
UITableViewDelegate,
UITableViewDataSource,
UIImagePickerControllerDelegate,
UINavigationControllerDelegate,
AreaDelegate,
BaseViewDelegate
>

@property (weak, nonatomic) IBOutlet UIButton *userImage;
@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (nonatomic , strong) UITableView * tableview;
@property (nonatomic , strong) UIImagePickerController * picker;
@property (nonatomic , strong) NSArray * titleArray;
@property (nonatomic , strong) UILabel * nickLbale;
@property (nonatomic , strong) UILabel * brithDayLable;
@property (nonatomic , strong) UILabel * addressLabel;
@property (nonatomic , strong) UILabel * referralLabel;
@property (nonatomic , strong) UIButton * manBtn;
@property (nonatomic , strong) UIButton * womenBtn;
@property (nonatomic , strong) UILabel * actullyNameLabel;
@property (nonatomic , strong) UILabel * referenceLabel;
@property (nonatomic , strong) NSString * referenceNum;
@property (nonatomic , strong) BrithDayView * BrithView ;

@property (strong, nonatomic)HDAreaChoiceView *areaChoiceView;

@end

@implementation PersonalInformationController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)setNavi
{
    self.title = @"个人资料";
}

-(void)viewWillAppear:(BOOL)animated
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSDictionary * dict = @{@"token":self.userToken};
    [HTTPTool POSTForm:[NSString stringWithFormat:@"%@member/person-info",BaseUrl] para:dict success:^(BOOL isSuccess, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        if (isSuccess) {
            self.nickLbale.text = self.nickName = [[responseObject objectForKey:@"data"] objectForKey:@"user_name"];
            self.gender = [[[responseObject objectForKey:@"data"] objectForKey:@"gender"] integerValue];
            if (![[[responseObject objectForKey:@"data"] objectForKey:@"birthday"] isKindOfClass:[NSNull class]]) {
                self.brithDay = [[responseObject objectForKey:@"data"] objectForKey:@"birthday"];
            }
            self.region_id = [[[responseObject objectForKey:@"data"] objectForKey:@"region_id"] integerValue];
            self.addressLabel.text = [[responseObject objectForKey:@"data"] objectForKey:@"region_name"];
            self.referenceNum = [[responseObject objectForKey:@"data"] objectForKey:@"promoter_phone"];
            // 实名认证状态
            self.actuallyName = [[[responseObject objectForKey:@"data"] objectForKey:@"verify"] integerValue];
            
            [self.tableview reloadData];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
    }];
}

- (void)setUI
{
    if (self.userImageString.length) {
        [self.userImage sd_setBackgroundImageWithURL:[NSURL URLWithString:self.userImageString] forState:(UIControlStateNormal)];
    }
    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 44) style:(UITableViewStyleGrouped)];
    self.tableview.dataSource = self;
    self.tableview.delegate = self;
    [self.view addSubview:self.tableview];
    [self.tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    self.tableview.tableHeaderView = self.headerView;
    [self.userImage.layer setMasksToBounds:YES];
    [self.userImage.layer setCornerRadius:40];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 5;
    }else
    {
        return 1;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.textLabel.textColor = TextMainColor;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    if (indexPath.section == 0) {
        cell.textLabel.text = self.titleArray[indexPath.row];
        
        
        if (indexPath.row == 1) {
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryNone;
            [cell.contentView addSubview:self.manBtn];
            [cell.contentView addSubview:self.womenBtn];
            
            [self.womenBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.offset(-20);
                make.centerY.equalTo(cell.contentView);
                make.size.mas_offset(CGSizeMake(40, 25));
            }];
            
            [self.manBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(self.womenBtn.mas_left).offset(-20);
                make.centerY.equalTo(cell.contentView);
                make.size.mas_offset(CGSizeMake(40, 25));
            }];
            if (self.gender == 2) {
                self.womenBtn.selected = YES;
                self.manBtn.selected = NO;
            }
            
        }else if(indexPath.row == 2){
            [cell.contentView addSubview:self.brithDayLable];
            [self.brithDayLable mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.offset(-10);
                make.centerY.equalTo(cell.contentView);
            }];
            if (self.brithDay) {
                self.brithDayLable.text = self.brithDay;
            }else
            {
                self.brithDayLable.text = @"未设置";
            }
            
            self.brithDayLable.font = FontSize(14);
            
        }else if (indexPath.row == 3){
            
            [cell.contentView addSubview:self.addressLabel];
            [self.addressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.offset(-10);
                make.centerY.equalTo(cell.contentView);
            }];
            
        }else if (indexPath.row == 0)  // 昵称
        {
            [cell.contentView addSubview:self.nickLbale];
            [self.nickLbale mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.offset(-10);
                make.centerY.equalTo(cell.contentView);
            }];
        }
        else if (indexPath.row == 4) // 推荐人
        {
            [cell.contentView addSubview:self.referralLabel];
            self.referralLabel.text = self.referenceNum.length > 0 ? self.referenceNum : @"未设置";
            [self.referralLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.offset(-10);
                make.centerY.equalTo(cell.contentView);
            }];
        }
    }
    else
    {
        cell.textLabel.text = @"实名认证";
        [cell.contentView addSubview:self.actullyNameLabel];
        [self.actullyNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.offset(-10);
            make.centerY.equalTo(cell.contentView);
        }];
        if (self.actuallyName == 0) {
            self.actullyNameLabel.text = @"未认证";
            
        }else if (self.actuallyName == 1)
        {
            self.actullyNameLabel.text = @"正在审核";
        }else if (self.actuallyName == 2)
        {
            self.actullyNameLabel.text = @"审核通过";
        }else if (self.actuallyName == 3)
        {
            self.actullyNameLabel.text = @"审核拒绝";
        }
    }
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
            {
                [self ToNickName];
            }
                break;
            case 1:
            {
                return;
            }
                break;
            case 2:
            {
                [self choiceBrith];
            }
                break;
            case 3:
            {
                [self changeArea];
            }
                break;
            case 4:
            {
                // 推荐人
                if (self.referenceNum.length > 0) {
                    return;
                }else
                {
                    [self ToRefrence];
                }
            }
                break;
                
            default:
                break;
        }
    }else
    {
//        实名认证
        if (self.actuallyName == 0) {
//            未认证
            [self ToRealName];
            
        }else if (self.actuallyName == 1)
        {
//            正在审核
            ResultController * vc = [[ResultController alloc]init];
            vc.imageName = @"icon_提交等待";
            vc.labelText = @"您的实名认证已提交\n我们会尽快处理，请耐心等待…";
            vc.isHiddenBtn = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }else if (self.actuallyName == 2)
        {
//            审核通过
            return;
        }else if (self.actuallyName == 3)
        {
//            审核拒绝
            AuditRefuseController * vc =[[AuditRefuseController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

- (void)ToRealName
{
    RealNameController * vc = [[RealNameController alloc]initWithNibName:@"RealNameController" bundle:[NSBundle mainBundle]];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)changeArea
{
    // ghd chnage
    self.zh_popupController = [zhPopupController new];
    self.zh_popupController.layoutType = zhPopupLayoutTypeBottom;
    [self.zh_popupController presentContentView:self.areaChoiceView duration:0.2 springAnimated:NO];
    
}

- (void)ToNickName
{
    NickNameViewController * vc = [[NickNameViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
//15184470299
- (void)ToRefrence
{
    ReferrerViewController * vc = [[ReferrerViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)getArea:(NSString *)area
{
    self.addressLabel.text = area;
}

- (void)choiceBrith
{
    self.zh_popupController = [zhPopupController new];
    self.zh_popupController.layoutType = zhPopupLayoutTypeBottom;
    [self.zh_popupController presentContentView:self.BrithView duration:0.2 springAnimated:NO];
    __weak typeof(self) weakSelf = self;
    self.BrithView.dateBlock = ^(NSString *dateString) {
        [MBProgressHUD showHUDAddedTo:weakSelf.view animated:YES];
        NSDictionary * dict = @{@"birthday":dateString,@"token":weakSelf.userToken};
        [HTTPTool POSTForm:[NSString stringWithFormat:@"%@member/edit-birthday",BaseUrl] para:dict success:^(BOOL isSuccess, id responseObject) {
            [MBProgressHUD hideHUDForView:weakSelf.view];
            if (isSuccess) {
                weakSelf.brithDayLable.text = dateString;
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:weakSelf.view];
        }];
    };
    self.BrithView.conBlock = ^{
        [weakSelf.zh_popupController dismiss];
    };
    self.BrithView.cancelBlock = ^{
        [weakSelf.zh_popupController dismiss];
    };
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setupPicker
{
    
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"" message:@"提示" preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction * photo = [UIAlertAction actionWithTitle:@"相机" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        self.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:self.picker animated:YES completion:nil];
    }];
    
    UIAlertAction * camera = [UIAlertAction actionWithTitle:@"相册" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        self.picker.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:self.picker animated:YES completion:nil];
        
    }];
    
    [alert addAction:photo];
    [alert addAction:camera];
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

#pragma mark 修改头像
- (IBAction)changeUserImage:(id)sender {
    [self setupPicker];
}
#pragma mark 修改头像
- (IBAction)changeImage:(id)sender {
    [self setupPicker];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSData * data = UIImageJPEGRepresentation(info[UIImagePickerControllerEditedImage], 0.5);
    NSDictionary * dict = @{@"token":self.userToken};
    
    [HTTPTool uploadImageWithURL:[NSString stringWithFormat:@"%@member/edit-portrait",BaseUrl] parameters:dict uploadImage:data success:^(BOOL isSuccess, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        if (isSuccess) {
            [self.userImage sd_setImageWithURL:[NSURL URLWithString:[[responseObject objectForKey:@"data"] objectForKey:@"picture_url"]] forState:(UIControlStateNormal)];
        }
         [self dismissViewControllerAnimated:YES completion:nil];
    } failure:^(NSError *error) {
         [self dismissViewControllerAnimated:YES completion:nil];
        [MBProgressHUD hideHUDForView:self.view];
    }];
}

- (void)changeSex:(UIButton *)sender
{
    NSInteger sex ;
    if (sender.tag == 1010) {
        sex = 1;
    }else
    {
        sex = 2;
    }
    [MBProgressHUD showMessage:@"正在修改性别" toView:self.view];
    NSDictionary * dict = @{@"token":self.userToken,@"gender":[NSString stringWithFormat:@"%ld",sex]};
    [HTTPTool POSTForm:[NSString stringWithFormat:@"%@member/edit-sex",BaseUrl] para:dict success:^(BOOL isSuccess, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        if (isSuccess) {
            self.gender = sex;
            if (sender.tag == 1010) {
                sender.selected = !sender.isSelected;
                sender.userInteractionEnabled = NO;
                self.womenBtn.selected = !sender.selected;
                self.womenBtn.userInteractionEnabled = YES;
            }else if (sender.tag == 1111){
                sender.selected = !sender.isSelected;
                self.manBtn.selected = !sender.selected;
                sender.userInteractionEnabled = NO;
                self.manBtn.userInteractionEnabled = YES;
            }
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
    }];
}

- (void)viewActionWithView:(UIView *)view tag:(NSInteger)tag data:(id)data {
    if ([view isKindOfClass:[HDAreaChoiceView class]]) {
        [self.zh_popupController dismiss];
        self.areaChoiceView = nil;
        
        WS(weakSelf)
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = @{@"token":self.userToken,
                                  @"region_id":[data strForKey:@"region_id"]};
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            [HTTPTool POSTForm:[NSString stringWithFormat:@"%@member/edit-region",BaseUrl] para:dic success:^(BOOL isSuccess, id responseObject) {
                [MBProgressHUD hideHUDForView:self.view];
                if (isSuccess) {
                    weakSelf.addressLabel.text = [data strForKey:@"region_name"];
                }
            } failure:^(NSError *error) {
                [MBProgressHUD hideHUDForView:self.view];
            }];
        }

    }
}

-(UIImagePickerController *)picker
{
    if (!_picker) {
        _picker = [[UIImagePickerController alloc]init];
        _picker.delegate = self;
        _picker.allowsEditing = YES;
    }
    return _picker;
}

-(UIButton *)manBtn
{
    if (!_manBtn) {
        _manBtn = [[UIButton alloc]init];
        [_manBtn setTitle:@"男" forState:(UIControlStateNormal)];
        [_manBtn setImage:Image(@"icon_未选中") forState:(UIControlStateNormal)];
        [_manBtn setImage:Image(@"icon_选中") forState:(UIControlStateSelected)];
        [_manBtn setTitleColor:TextAssistColor forState:(UIControlStateNormal)];
        _manBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
        _manBtn.selected = YES;
        [_manBtn addTarget:self action:@selector(changeSex:) forControlEvents:(UIControlEventTouchUpInside)];
        _manBtn.tag = 1010;
    }
    return _manBtn;
}

- (UIButton *)womenBtn
{
    if (!_womenBtn) {
        _womenBtn = [[UIButton alloc]init];
        [_womenBtn setTitle:@"女" forState:(UIControlStateNormal)];
        [_womenBtn setImage:Image(@"icon_未选中") forState:(UIControlStateNormal)];
        [_womenBtn setImage:Image(@"icon_选中") forState:(UIControlStateSelected)];
        [_womenBtn setTitleColor:TextAssistColor forState:(UIControlStateNormal)];
        _womenBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
        [_womenBtn addTarget:self action:@selector(changeSex:) forControlEvents:(UIControlEventTouchUpInside)];
        _womenBtn.tag = 1111;
    }
    return _womenBtn;
}

-(UILabel *)nickLbale
{
    if (!_nickLbale) {
        _nickLbale = [[UILabel alloc]init];
        _nickLbale.textColor = TextAssistColor;
        _nickLbale.text = self.nickName;
        _nickLbale.font = FontSize(14);
    }
    return _nickLbale;
}

-(UILabel *)brithDayLable
{
    if (!_brithDayLable) {
        _brithDayLable = [[UILabel alloc]init];
        _brithDayLable.textColor = TextAssistColor;
        _brithDayLable.font = FontSize(14);
        _brithDayLable.text = self.brithDay ? self.brithDay : @"未设置";
    }
    return _brithDayLable;
}

-(UILabel *)addressLabel
{
    if (!_addressLabel) {
        _addressLabel = [[UILabel alloc]init];
        _addressLabel.textColor = TextAssistColor;
        _addressLabel.font = FontSize(14);
    }
    return _addressLabel;
}

-(UILabel *)referralLabel
{
    if (!_referralLabel) {
        _referralLabel = [[UILabel alloc]init];
        _referralLabel.textColor = TextAssistColor;
        _referralLabel.font = FontSize(14);
    }
    return _referralLabel;
}

- (UILabel *)actullyNameLabel
{
    if (!_actullyNameLabel) {
        _actullyNameLabel = [[UILabel alloc]init];
        _actullyNameLabel.textColor = TextAssistColor;
        _actullyNameLabel.font = FontSize(14);
    }
    return _actullyNameLabel;
}

-(NSArray *)titleArray
{
    if (!_titleArray) {
        _titleArray = @[@"昵称",@"性别",@"生日",@"所在地区",@"推荐人"];
    }
    return _titleArray;
}

-(BrithDayView *)BrithView
{
    if (!_BrithView) {
        _BrithView = [[[NSBundle mainBundle] loadNibNamed:@"BrithDayView" owner:self options:nil] lastObject];
        _BrithView.backgroundColor = [UIColor clearColor];
        _BrithView.frame = CGRectMake(0, 0 , kScreenWidth, kScreenHeight);
        _BrithView.datePicker.backgroundColor = [UIColor whiteColor];
    }
    return _BrithView;
}

- (HDAreaChoiceView *)areaChoiceView {
    if (!_areaChoiceView) {
        _areaChoiceView = [[HDAreaChoiceView alloc] initWithFrame:CGRectMake(0, kScreenHeight/2.0, kScreenWidth, kScreenHeight/2.0)];
        _areaChoiceView.delegate = self;
    }
    return _areaChoiceView;
}



@end
